<template>
  <!-- 写游记页面 -->
  <div class="contianer">
    <!-- 发表新攻略列 -->
    <div class="details" v-loading="isLoading">
      <h2>发表新攻略</h2>
      <p class="create-des">分享你的个人游记，让更多人看到哦</p>
      <el-form ref="form" :model="form" label-position="left">
        <!-- 标题输入框 -->
        <el-form-item>
          <el-input v-model="form.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <!-- 富文本编辑器 -->
        <el-form-item>
          <!-- useCustomImageHandler为true：禁止富文本框自动将图片转成 base64；它默认上传图片时是将图片转base64保存的,如果需要上传到服务器,则需要 -->
          <!-- 使用no-ssr标签将富文本编辑器套住，该组件用于设置组件不在服务器渲染中呈现。
          防止报错服务端和客户端渲染的dom树不一样：服务端渲染和客户端虚拟DOM树内容不匹配;-->
          <no-ssr>
            <vue-editor
              v-model="form.content"
              :useCustomImageHandler="true"
              @image-added="imgUpload"
              :editor-toolbar="customToolbar"
            />
          </no-ssr>
        </el-form-item>
        <!-- 选择城市 -->
        <el-form-item class="selectcity" label="选择城市" label-width="70px">
          <el-col :span="7">
            <!-- input框的远程搜索 -->
            <!-- fetch-suggestions 输入建议时候触发的方法 -->
            <!-- select 点击选中建议项时触发 -->
            <!-- :trigger-on-focus="false" 获取焦点的时候不自动加载建议列表 -->
            <el-autocomplete
              :fetch-suggestions="queryCitySearch"
              placeholder="请选择城市"
              @select="handleCitySelect"
              class="el-autocomplete"
              v-model="form.city"
              :trigger-on-focus="false"
            ></el-autocomplete>
          </el-col>
        </el-form-item>
        <!-- 发布或者保存草稿 -->
        <el-form-item>
          <el-button type="primary" size="small" @click="submitAtricle">发布</el-button>
          <span class="or">或者</span>
          <span class="savedrafts">
            <a href="#" @click.prevent.stop="saveDrafts">保存到草稿</a>
          </span>
        </el-form-item>
      </el-form>
    </div>
    <!-- 草稿箱 -->
    <div class="draft">
      <div class="draftcon">
        <h4>草稿箱（{{draftItem.length}}）</h4>
        <!-- 草稿列表 -->
        <div class="draft-item" v-for="(item,index) of draftItem" :key="index">
          <p class="draft-title">
            <a href="#" @click.prevent="secDraft(index)">{{item.title}}</a>
          </p>
          <p class="draft-info">
            <span class="time">{{item.time |formatDate}}</span>
            <span class="handler">
              <i class="el-icon-edit" @click="secDraft(index)"></i>
              <i class="el-icon-delete" @click="delDraft(index)"></i>
            </span>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 引入富文本编辑器
// import { VueEditor } from "vue2-editor";
export default {
  filters: {
    formatDate(val) {
      let arr = val
        .toLocaleDateString()
        .split("/")
        .map((v) => {
          if (v.length == 1) {
            return (v = "0" + v);
          }
          return v;
        });
      return arr.join("-");
    },
  },
  data() {
    return {
      isLoading: false,
      form: {
        title: "",
        content: "",
        city: "",
      },
      customToolbar: [
        ["bold", "italic", "underline", "strike"], //加粗 斜体 下划线
        [{ header: 1 }, { header: 2 }], //h1 h2 标题
        [{ list: "ordered" }, { list: "bullet" }], //有序列表 无序列表
        ["image"], //图片
        // [{ color: [] },{ align: [] }], // 字体颜色 { background: [] } 字体背景颜色
        // [{ font: [] }],字体样式
      ],
      // 草稿列表
      draftItem: [],
    };
  },
  methods: {
    //处理富文本框自定义上传图片逻辑 点击上传后返回4个参数
    // file 选中的图片
    // Editor 是当前编辑器实例对象
    // cursorLocation 当前光标所在位置
    // resetUploader 这是上传完图片用来重新初始化上传功能的函数
    // 富文本框图片上传方法
    imgUpload(file, Editor, cursorLocation, resetUploader) {
      // 1.上传图片
      let formData = new FormData();
      formData.append("files", file);
      // console.log("上传图片");
      this.$axios({
        url: "/upload",
        method: "post",
        data: formData,
      })
        .then((result) => {
          // console.log(result);
          let url = result.data[0].url; // Get url from response
          // 拿到图片地址
          // 要放入富文本框当中
          // Editor.insertEmbed(cursorLocation, "image", url);这是编辑器自带函数, 可以往编辑框内放入内容 三个参数 位置 / 类型 / 内容
          Editor.insertEmbed(
            cursorLocation,
            "image",
            this.$axios.defaults.baseURL + url
          );
          // 将图片插入到富文本框之后还要重置上传功能
          resetUploader();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 点击发布文章触发事件
    submitAtricle() {
      // 验证表单数据
      const rules = {
        title: {
          value: this.form.title,
          message: "文章标题不能为空!",
        },
        content: {
          value: this.form.content,
          message: "文章内容不能为空!",
        },
        city: {
          value: this.form.city,
          message: "选择城市不能为空!",
        },
      };

      let vaild = true; //验证结果
      Object.keys(rules).forEach((v) => {
        if (!vaild) return;
        if (!rules[v].value) {
          vaild = false;
          this.$confirm(rules[v].message, "提示", {
            confirmButtonText: "确定",
            showCancelButton: false,
            type: "warning",
          });
        }
      });

      if (!vaild) return;

      //通过Vuex中state获取用户登录信息：token值
      const {
        user: { userInfo },
      } = this.$store.state;

      // console.log("发送请求");
      // console.log(this.form);

      if (!userInfo.token) {
        this.$message({
          message: "请先登录",
          type: "warning",
        });
        // console.log(JSON.stringify(this.form));
        localStorage.setItem("curdraft", JSON.stringify(this.form));
        this.$router.push({ path: `/user/login?editing=true` });
      } else {
        this.isLoading = true;
        this.$axios({
          url: "/posts",
          method: "post",
          data: this.form,
          headers: {
            Authorization: `Bearer ${userInfo.token || "NO TOKEN"}`,
          },
        })
          .then((res) => {
            console.log(res);
            if (res.status == 200) {
              setTimeout(() => {
                this.form.title = "";
                this.form.content = "";
                this.form.city = "";

                this.isLoading = false;
                this.$confirm("发布成功！是否跳转旅游攻略页?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "success",
                })
                  .then(() => {
                    this.$router.push({ path: "/post" });
                  })
                  .catch(() => {});
              }, 1500);
            }
          })
          .catch((err) => {
            this.isLoading = false;
          });
      }
    },
    // 输入城市时候触发的方法
    // value 是输入的值，cb是回调函数，接收要展示的列表
    queryCitySearch(value, cb) {
      // 调用air封装好的方法
      this.$store
        .dispatch("air/getFromCity", value.trim())
        .then((res) => {
          if (res.length > 0) {
            this.form.city = res[0].value;
          }
          if (res) {
            cb(res);
          }
        })
        .catch((err) => {
          if (err) {
            cb([]);
          }
        });
    },
    // 选择对应城市时候触发的方法
    handleCitySelect(item) {
      console.log("选择了" + item.value);
      this.form.city = item.value;
    },
    // 初始化草稿箱方法
    showDraft() {
      let draftList = JSON.parse(localStorage.getItem("draftList")) || [];
      this.draftItem = [];
      draftList.forEach((v) => {
        this.draftItem.push({ title: v.title, time: new Date() });
      });
    },
    // 保存草稿
    saveDrafts() {
      // 判断是否写了标题
      if (this.form.title.trim() == "") {
        this.$message({
          message: "请添加一个标题~",
          type: "warning",
        });
        return;
      }

      // 判断当前草稿箱长度是否超过10 超过了就提醒用户
      if (this.draftItem.length >= 10) {
        this.$message({
          message: "最多只能保存10份草稿哦~",
          type: "warning",
        });
        return;
      }

      // 1.看看本地草稿中有没有有就从本地取
      let draftList = JSON.parse(localStorage.getItem("draftList")) || [];

      // 2.遍历本地的草稿，看看是否保存的标题在本地草稿中存在
      if (JSON.parse(localStorage.getItem("draftList"))) {
        JSON.parse(localStorage.getItem("draftList")).forEach((item, index) => {
          // 2.1如果存在就将这个删除
          if (item.title == this.form.title) {
            draftList.splice(index, 1);
          }
        });
      }
      // 3.再将当前写的文章添加到本地草稿列表
      draftList.push(this.form);
      // 4.存储到本地
      localStorage.setItem("draftList", JSON.stringify(draftList));
      //5.渲染草稿箱列表
      this.draftItem = [];
      draftList.forEach((item) => {
        this.draftItem.push({ title: item.title, time: new Date() });
      });

      this.form.title = "";
      this.form.content = "";
      this.form.city = "";
      this.$message({ message: "保存成功", type: "success" });
    },
    // 选择草稿
    secDraft(index) {
      let drafts = JSON.parse(localStorage.getItem("draftList")).slice(
        index,
        index + 1
      );
      this.form = drafts[0];
    },
    // 删除草稿
    delDraft(index) {
      this.$confirm("确定删除该草稿吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let draftList = JSON.parse(localStorage.getItem("draftList"));
          draftList.splice(index, 1);
          localStorage.setItem("draftList", JSON.stringify(draftList));
          //重新渲染草稿箱列表
          this.showDraft();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {});
    },
  },
  watch: {},
  mounted() {
    this.showDraft();

    // 从登录页面跳转过来判断是否写了当前页面
    let curdraft = JSON.parse(localStorage.getItem("curdraft"));
    if (curdraft) {
      this.form = curdraft;
      localStorage.removeItem("curdraft");
    }
  },
  components: {},
};
</script>

<style lang="less" scoped>
.contianer {
  display: flex;
  justify-content: space-between;
  width: 1000px;
  min-height: 300px;
  margin: 20px auto 0px;
  // 发表攻略详细样式
  .details {
    width: 750px;
    h2 {
      font-weight: 400;
      font-size: 22px;
      margin-bottom: 10px;
    }
    .create-des {
      font-size: 12px;
      color: #999;
      margin-bottom: 10px;
    }
    .or {
      margin-left: 10px;
    }
    .selectcity {
      margin-top: 80px;
    }
    .savedrafts {
      a {
        color: orange;
        &:hover {
          text-decoration: underline;
        }
      }
    }
    // 富文本编辑器样式
    .quillWrapper {
      height: 350px;
    }
  }
  // 草稿箱样式
  .draft {
    width: 225px;
    box-sizing: border-box;
    .draftcon {
      width: 100%;
      padding: 10px;
      box-sizing: border-box;
      min-height: 150px;
      border: 1px solid #ddd;
      h4 {
        margin-bottom: 10px;
        font-weight: 400;
        color: #666;
        font-size: 16px;
      }
      .draft-item {
        margin-bottom: 10px;
        font-size: 14px;
        .draft-title {
          word-break: break-all;
          text-overflow: ellipsis;
          overflow: hidden;
          a {
            &:hover {
              color: orange;
              text-decoration: underline;
            }
          }
        }
        .draft-info {
          display: flex;
          justify-content: space-between;
          .time {
            color: #999;
          }
          .handler {
            i {
              cursor: pointer;
              font-size: 16px;
              margin-right: 4px;
            }
          }
        }
      }
    }
  }
}
</style>